package com.zlj.jdbc.batch;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

import com.zlj.jdbc.demo.JdbcUtils;

/**
 * 使用PreparedStatement执行批处理。
 * 因为mysql的批处理默认是关闭的，所以需要在dbConfig.properties中设置开启批处理
 * 即：url = jdbc:mysql://localhost:3306/testsql?rewriteBatchedStatements = true
 * 
 * @author bashen
 *
 */
public class BatchDemo {
	/**
	 * 使用PreparedStatement执行批处理
	 * 因为mysql的批处理默认是关闭的，所以需要在dbConfig.properties中设置开启批处理
	 * 即：url = jdbc:mysql://localhost:3306/testsql?rewriteBatchedStatements = true
	 */
    @Test
	public void test01() {
    	Connection conn = null;
    	PreparedStatement statement = null;
    	try {
    		conn = JdbcUtils.getConnection();
    		String sql = "insert into student values(?,?,?,?)";
    		statement = conn.prepareStatement(sql);
    		//添加参数
    		for(int i = 0; i < 10000; i++) {
    			statement.setInt(1, i + 1);
    			statement.setString(2, "tom" + i);
    			statement.setInt(3, i);
    			statement.setString(4, i % 2 == 0 ? "男" : "女");
    			//添加批，把这一组参数添加到集合中
    			statement.addBatch(); 
    		}
    		long start = System.currentTimeMillis();
    		statement.executeBatch();  //执行批
    		long end = System.currentTimeMillis();
    		System.out.println("执行批一共花了：" + (end - start) + "毫秒！");
    	} catch(Exception e) {
    		throw new RuntimeException(e);
    	} finally {
    		try {
    			if(statement != null) statement.close();
    			if(conn != null) conn.close();
    		} catch(Exception e) {
    			throw new RuntimeException(e);
    		}
    	}
	}
}
